package com.csw.mysqldate.interceptor.traceId;

import cn.hutool.core.util.IdUtil;
import com.csw.mysqldate.util.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 在启动类上要加注解
 *
 * @ServletComponentScan
 */
@Slf4j
@WebFilter(filterName = "TraceIdFilter", urlPatterns = "/*")
public class TraceIdFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
        if (request.getAttribute("requestId") == null && request.getHeader("requestId") == null) {
            //进来的是主方法
            log.info("【进的是主方法】");
            request.setAttribute("requestId", SnowflaketoBase62Id());
        }


        // 生成traceId并放入MDC
        MDC.put("traceId", TraceIdFilter.getRequestId());

        log.info("【TraceIdFilter进来了】");
        try {
            // 继续执行请求链
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            // 请求结束后清除MDC中的值
            MDC.clear();
        }
        log.info("【TraceIdFilter结束了】");
    }

    @Override
    public void destroy() {
    }

    private static final char[] BASE_62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();

    public static String SnowflaketoBase62Id() {
        Long snowflakeId = IdUtil.getSnowflake().nextId();
        StringBuilder base62 = new StringBuilder();
        do {
            int remainder = (int) (snowflakeId % 62);
            base62.insert(0, BASE_62_CHARS[remainder]);
            snowflakeId = snowflakeId / 62;
        } while (snowflakeId > 0);

        return base62.toString();
    }

    public static String getRequestId() {
        HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
        String requestId;
        if (request.getAttribute("requestId") != null) {
            requestId = request.getAttribute("requestId").toString();
        } else if (request.getHeader("requestId") != null) {
            requestId = request.getHeader("requestId").toString();
        } else {
            requestId = null;
        }
        return requestId;
    }
}